package cn.winwintech.Incense.dao.impl;

import java.sql.Timestamp;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.base.webapp.respm.ResException;

import cn.winwintech.Incense.dao.UserDao;
import cn.winwintech.Incense.exception.ResExceptionFactory;
import cn.winwintech.Incense.model.Operation;
import cn.winwintech.Incense.model.User;

@Repository("userDao")
public class UserDaoImpl extends GenericDaoImpl implements UserDao {
	public static final int pageSize = 50;
	@Override
	public User findUserById(long id) {
		return persistence.find(User.class, id);
	}

	@Override
	public Operation findOperationById(long id) {
		return persistence.find(Operation.class, id);
	}


	@Override
	public int findTotalNum(long maxUpdateAt) {
		Timestamp update = new Timestamp(maxUpdateAt);
		String sql = "select count (m)  from Operation m where m.updateAt > ?  order by updateAt ";
		return persistence.numberBySqlOf(sql, update).intValue();
	}

	@Override
	public List<Operation> findOperationList(int page, long maxUpdateAt) {
		Timestamp update = new Timestamp(maxUpdateAt);
		String sql = "select m from Operation m where m.updateAt > ?  order by updateAt ";
		return persistence.findBySqL(page, pageSize, sql, update);
	}

	@Override
	public boolean isPhoneExist(String userName) {
		return persistence.exist(User.class, "userName", userName);
	}

	@Override
	public User findUserByPhone(String userName) {
		return persistence.findSingle(User.class, "userName", userName);
	}

	@Override
	public User findUserByToken(String token) {
		return persistence.findSingle(User.class, "token", token);
	}

	@Override
	public User findUserByTokenNotNull(String token) throws ResException {
		User user = findUserByToken(token);
		if (user == null) {
			throw ResExceptionFactory.tokenInvalid();
		}
		if (user.getTokenExpire().getTime() < System.currentTimeMillis()) {
			throw ResExceptionFactory.tokenExpire();
		}
		return user;
	}

	@Override
	public User createUser(String name, String userName, String password, String avatar) {
		User user = new User();
		user.setName(name);
		user.setUserName(userName);
		user.setPassword(password);
		user.setAvatar(avatar);
		persistence.save(user);
		return user;
	}

	public String refreshToken(User user) {
		user.setToken(user.getUserName() + System.currentTimeMillis());
		user.setTokenExpire(new Timestamp(System.currentTimeMillis() + TOKEN_EXPIRE_TIME));
		persistence.save(user);
		return user.getToken();
	}

}
